package com.mzj.saas.mservice.announcement.service;

import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.enums.AnnouncementTypeEnum;
import com.mzj.saas.commons.enums.AnnouncementViewStatusEnum;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.announcement.entity.Announcement;
import com.mzj.saas.mservice.announcement.entity.AnnouncementUser;
import com.mzj.saas.mservice.announcement.repository.AnnouncementRepository;
import com.mzj.saas.mservice.announcement.repository.AnnouncementUserRepository;
import com.mzj.saas.mservice.announcement.vo.*;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.backlog.vo.AnnouncementApiData;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.sys.utils.SqlUtils;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AnnouncementAppService {
    private static final Logger log = LoggerFactory.getLogger(AnnouncementAppService.class);

    private static final String AN_COLUM = "SELECT a.id,a.type,a.title,a.home_pic as homePic,a.release_time as releaseTime";
    private static final String AN_FROM_MONITOR = " FROM saas_house h";
    private static final String AN_ORDER = " ORDER BY a.release_time DESC";
    private static final String SQL_PAGE = " LIMIT ? OFFSET ?";

    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private AnnouncementRepository announcementRepository;
    @Autowired
    private RedisService redisService;
    @Autowired
    private AnnouncementUserRepository announcementUserRepository;
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    public ResultBean<List<Map<String, Object>>> findCommunity(String cityName) {
        try {
            if (StringUtils.isBlank(cityName)) {
                return ResultBean.failedResultOfParamWithMsg("城市名为空");
            }

            Area area = areaRepository.findByName(cityName);
            if (area == null) {
                return ResultBean.failedResultWithMsg("城市数据不存在");
            }
            Long cityId = area.getId();
            List<Community> communitys = communityRepository.findByCityIdAndStatus(cityId, 1);
            List<Map<String, Object>> list = new ArrayList<>();
            for (Community community : communitys) {
                Map<String, Object> map = new HashMap<>();
                map.put("communityId", community.getId());
                map.put("communityName", community.getName());
                list.add(map);
            }

            return ResultBean.successfulResult(list);
        } catch (Exception e) {
            log.error("AnnouncementAppService findCommunity Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<List<PublicAnnouncementListVO>> publicAnnouncementList(String accessToken, String communityId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Integer loginType = tokenRedisVo.getLoginType();

            if (StringUtils.isBlank(communityId)) {
                return ResultBean.failedResultOfParamWithMsg("小区id为空");
            }

            Optional<Community> communityOpt = communityRepository.findById(communityId);
            if (!communityOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("小区不存在");
            }
            Community community = communityOpt.get();
            Long areaId = community.getCommunityId();

            ArrayList<PublicAnnouncementListVO> list = new ArrayList<>();

            //平台公告
            List<Map<String, Object>> platformList = jdbcTemplate.queryForList("SELECT a.title,a.release_time AS releaseTime FROM saas_announcement a WHERE a.status = 1 AND a.type IN (4)\n" +
                    "AND a.release_time = (SELECT MAX(a.release_time) FROM saas_announcement a WHERE a.status = 1 AND a.type IN (4) )\n");
            if (!platformList.isEmpty()) {
                Map<String, Object> map = platformList.get(0);
                String title = map.get("title").toString();
                String releaseTime = map.get("releaseTime").toString();

                PublicAnnouncementListVO vo = new PublicAnnouncementListVO();
                vo.setType(AnnouncementTypeEnum.PLATFORM.getValue());
                vo.setTitle(title);
                vo.setReleaseTime(DateUtils.format(releaseTime, DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                //未阅读数量
                Long count = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM saas_announcement a \n" +
                        "WHERE 1 = 1 AND a.status = 1 AND  a.type IN (4) \n" +
                        "AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND a.type IN (4) AND u.user_id = ?)\n", Long.class, userId);
                if (count > 0) {
                    vo.setViewStatus(AnnouncementViewStatusEnum.UN_READ.getValue());
                } else {
                    vo.setViewStatus(AnnouncementViewStatusEnum.READ.getValue());
                }
                list.add(vo);
            }

            //企业公告
            if (loginType == 1) {
                Long enterpriseId = tokenRedisVo.getEnterpriseId();
                List<Map<String, Object>> communityList = jdbcTemplate.queryForList("SELECT a.title,a.release_time AS releaseTime FROM saas_announcement a WHERE a.status = 1 AND a.type IN (1) AND a.org_id = ?\n" +
                        "AND a.release_time = (SELECT MAX(a.release_time) FROM saas_announcement a WHERE a.status = 1 AND a.type IN (1) AND a.org_id = ?)\n", enterpriseId, enterpriseId);
                if (!communityList.isEmpty()) {
                    Map<String, Object> map = communityList.get(0);
                    String title = map.get("title").toString();
                    String releaseTime = map.get("releaseTime").toString();

                    PublicAnnouncementListVO vo = new PublicAnnouncementListVO();
                    vo.setType(AnnouncementTypeEnum.ENTERPRISE.getValue());
                    vo.setTitle(title);
                    vo.setReleaseTime(DateUtils.format(releaseTime, DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                    //未阅读数量
                    List<Object> args = new ArrayList<>();
                    args.add(enterpriseId);
                    args.add(enterpriseId);
                    args.add(userId);
                    Long count = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM saas_announcement a\n" +
                                    "WHERE 1 = 1  AND a.status = 1 AND  a.type IN (1)  AND a.org_id = ? \n" +
                                    "AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND a.type IN (1) AND a.org_id = ? AND u.user_id = ?)\n",
                            args.toArray(), Long.class);
                    if (count > 0) {
                        vo.setViewStatus(AnnouncementViewStatusEnum.UN_READ.getValue());
                    } else {
                        vo.setViewStatus(AnnouncementViewStatusEnum.READ.getValue());
                    }
                    list.add(vo);
                }
            }

            //社区公告
            List<Map<String, Object>> communityList = jdbcTemplate.queryForList("SELECT a.title,a.release_time AS releaseTime FROM saas_announcement a WHERE a.status = 1 AND a.type IN (2,5) AND a.area_id = ?\n" +
                    "AND a.release_time = (SELECT MAX(a.release_time) FROM saas_announcement a WHERE a.status = 1 AND a.type IN (2,5) AND a.area_id = ?)\n", areaId, areaId);
            if (!communityList.isEmpty()) {
                Map<String, Object> map = communityList.get(0);
                String title = map.get("title").toString();
                String releaseTime = map.get("releaseTime").toString();

                PublicAnnouncementListVO vo = new PublicAnnouncementListVO();
                vo.setType(AnnouncementTypeEnum.COMMUNITY.getValue());
                vo.setTitle(title);
                vo.setReleaseTime(DateUtils.format(releaseTime, DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                //未阅读数量
                List<Object> args = new ArrayList<>();
                args.add(areaId);
                args.add(areaId);
                args.add(userId);
                Long count = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM saas_announcement a\n" +
                                "WHERE 1 = 1  AND a.status = 1 AND  a.type IN (2,5)  AND a.area_id = ? \n" +
                                "AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND a.type IN (2,5)  AND a.area_id = ? AND u.user_id = ?)\n",
                        args.toArray(), Long.class);
                if (count > 0) {
                    vo.setViewStatus(AnnouncementViewStatusEnum.UN_READ.getValue());
                } else {
                    vo.setViewStatus(AnnouncementViewStatusEnum.READ.getValue());
                }
                list.add(vo);
            }

            //小区公告
            List<Map<String, Object>> plotList = jdbcTemplate.queryForList("SELECT a.title,a.release_time AS releaseTime FROM saas_announcement a WHERE a.status = 1 AND a.type IN (3) AND a.community_id = ?\n" +
                    "AND a.release_time = (SELECT MAX(a.release_time) FROM saas_announcement a WHERE a.status = 1 AND a.type IN (3) AND a.community_id = ?)\n", communityId, communityId);
            if (!plotList.isEmpty()) {
                Map<String, Object> map = plotList.get(0);
                String title = map.get("title").toString();
                String releaseTime = map.get("releaseTime").toString();

                PublicAnnouncementListVO vo = new PublicAnnouncementListVO();
                vo.setType(AnnouncementTypeEnum.PLOT.getValue());
                vo.setTitle(title);
                vo.setReleaseTime(DateUtils.format(releaseTime, DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                //未阅读数量
                List<Object> args = new ArrayList<>();
                args.add(communityId);
                args.add(communityId);
                args.add(userId);
                Long count = jdbcTemplate.queryForObject("SELECT COUNT(1) FROM saas_announcement a \n" +
                                "WHERE 1 = 1 AND a.status = 1 AND a.type IN (3) AND a.community_id = ? \n" +
                                "AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND a.type IN (3) AND a.community_id = ? AND u.user_id = ?)\n",
                        args.toArray(), Long.class);
                if (count > 0) {
                    vo.setViewStatus(AnnouncementViewStatusEnum.UN_READ.getValue());
                } else {
                    vo.setViewStatus(AnnouncementViewStatusEnum.READ.getValue());
                }
                list.add(vo);
            }

            return ResultBean.successfulResult(list);
        } catch (Exception e) {
            log.error("AnnouncementAppService publicAnnouncementList Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<AnnouncementApiData<AnnouncementListVO>> announcementList(String accessToken, Integer viewStatus, Integer type, String communityId, Integer pageNumber, Integer pageSize) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            AnnouncementApiData<AnnouncementListVO> announcementApiData = new AnnouncementApiData<>();
            if (viewStatus == null) {
                return ResultBean.failedResultOfParamWithMsg("阅读状态为空");
            }
            // if (type == null) {
            //     return ResultBean.failedResultOfParamWithMsg("公告类型为空");
            // }
            if (StringUtils.isBlank(communityId)) {
                return ResultBean.failedResultOfParamWithMsg("小区id为空");
            }

            Optional<Community> communityOpt = communityRepository.findById(communityId);
            if (!communityOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("小区不存在");
            }
            Community community = communityOpt.get();
            Long areaId = community.getCommunityId();

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            List<Object> args1 = new ArrayList<>();
            // where.append(" where 1 = 1 and a.STATUS = 1 ");
            // where.append(" and a.STATUS = 1 ");
            List<Integer> types = new ArrayList<>();

            if (type != null) {
                where.append(" and a.type in ");
                //社区公告查社区和公示2种公告
                if (type == AnnouncementTypeEnum.COMMUNITY.getValue()) {
                    types.add(AnnouncementTypeEnum.COMMUNITY.getValue());
                    types.add(AnnouncementTypeEnum.PUBLICITY.getValue());
                } else {
                    types.add(type);
                }
                where.append(SqlUtils.foreachIn(types.size()));
                args.addAll(types);

                //公告类型查询条件
                if (type == AnnouncementTypeEnum.ENTERPRISE.getValue()) {
                    where.append(" and a.org_id = ?");
                    args.add(enterpriseId);
                } else if (type == AnnouncementTypeEnum.COMMUNITY.getValue()) {
                    where.append(" and a.area_id = ?");
                    args.add(areaId);
                } else if (type == AnnouncementTypeEnum.PLOT.getValue()) {
                    where.append(" and a.community_id = ?");
                    args.add(communityId);
                }
            }

            //阅读状态
            String from = "";

            if (viewStatus == 0) {
                from = " FROM saas_announcement a";
            } else if (viewStatus == 1) {
                from = " from saas_announcement a left join saas_announcement_user u on a.id = u.announcement_id ";
                where.append(" and u.user_id = ?");
                args.add(userId);
            } else if (viewStatus == 2) {
                from = " FROM saas_announcement a";
                if (type == AnnouncementTypeEnum.PLATFORM.getValue()) {
                    where.append(" AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND u.user_id = ? and a.type IN ");
                    args.add(userId);
                    where.append(SqlUtils.foreachIn(types.size()) + ")");
                    args.addAll(types);
                } else if (type == AnnouncementTypeEnum.ENTERPRISE.getValue()) {
                    where.append(" AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND a.org_id = ? AND u.user_id = ? and a.type IN ");
                    args.add(enterpriseId);
                    args.add(userId);
                    where.append(SqlUtils.foreachIn(types.size()) + ")");
                    args.addAll(types);
                } else if (type == AnnouncementTypeEnum.COMMUNITY.getValue()) {
                    where.append(" AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND a.area_id = ? AND u.user_id = ? and a.type IN ");
                    args.add(areaId);
                    args.add(userId);
                    where.append(SqlUtils.foreachIn(types.size()) + ")");
                    args.addAll(types);
                } else if (type == AnnouncementTypeEnum.PLOT.getValue()) {
                    where.append(" AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE 1 = 1 AND a.status = 1 AND a.community_id = ? AND u.user_id = ? and a.type IN ");
                    args.add(communityId);
                    args.add(userId);
                    where.append(SqlUtils.foreachIn(types.size()) + ")");
                    args.addAll(types);
                }
            }
            //查询出未读的总数
            String sql = "SELECT count(1) FROM saas_announcement a WHERE a.STATUS = 1 \n" +
                    "\tAND a.id NOT IN ( SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE u.user_id = ? ) \n" +
                    "\tAND ( a.community_id = ? OR a.area_id = ? ) ";
            args1.add(userId);
            args1.add(communityId);
            args1.add(areaId);
            Integer num = jdbcTemplate.queryForObject(sql, Integer.class, args1.toArray());
            List<AnnouncementListVO> list = new ArrayList<>();
            //if (pageSize > 9 ) {
            //    //where.append(" where 1 = 1 and a.STATUS = 1 ");
            //    where.append(" where 1 = 1 and a.STATUS = 1 and ( a.community_id = ? or a.area_id = ? ) ");
            //    args.add(communityId);
            //    args.add(areaId);
            //    args.add(pageSize);
            //    args.add(pageNumber * pageSize);
            //    list = jdbcTemplate.query(AN_COLUM + from + where + AN_ORDER + SQL_PAGE, new BeanPropertyRowMapper<>(AnnouncementListVO.class), args.toArray());
            //} else {
            //    where.append(" where 1 = 1 and a.STATUS = 1 and ( a.community_id = ? or a.area_id = ? ) ");
            //    args.add(communityId);
            //    args.add(areaId);
            //    args.add(pageSize);
            //    args.add(pageNumber * pageSize);
            //    list = jdbcTemplate.query(AN_COLUM + from + where + AN_ORDER + SQL_PAGE, new BeanPropertyRowMapper<>(AnnouncementListVO.class), args.toArray());
            //}
            //修复小程序不显示平台公告 20230414小龙
                where.append(" where 1 = 1 and a.STATUS = 1 and ( a.community_id = ? or a.area_id = ? or a.type = 4) ");
                args.add(communityId);
                args.add(areaId);
                args.add(pageSize);
                args.add(pageNumber * pageSize);
                list = jdbcTemplate.query(AN_COLUM + from + where + AN_ORDER + SQL_PAGE, new BeanPropertyRowMapper<>(AnnouncementListVO.class), args.toArray());
            for (AnnouncementListVO vo : list) {
                AnnouncementUser announcementUser = announcementUserRepository.findByAnnouncementIdAndUserId(vo.getId(), userId);
                if (viewStatus == 0) {
                    if (announcementUser == null) {
                        vo.setViewStatus(AnnouncementViewStatusEnum.UN_READ.getValue());
                    } else {
                        vo.setViewStatus(AnnouncementViewStatusEnum.READ.getValue());
                    }
                } else if (viewStatus == 1) {
                    vo.setViewStatus(AnnouncementViewStatusEnum.READ.getValue());
                } else if (viewStatus == 2) {
                    vo.setViewStatus(AnnouncementViewStatusEnum.UN_READ.getValue());
                }
                vo.setReleaseTime(DateUtils.format(vo.getReleaseTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));
            }

            for (int j = list.size() - 1; j >= 0; j--) {
                Long id = list.get(j).getId();
                AnnouncementUser announcementUser = announcementUserRepository.findByAnnouncementIdAndUserId(id, userId);
                if (announcementUser != null) {
                    Integer viewStatus1 = announcementUser.getViewStatus();
                    if (viewStatus1 != null && viewStatus1 == 3 ) {
                        list.remove(j);
                    }
                }
            }
            announcementApiData.setData(list);
            announcementApiData.setNum(num);
            return ResultBean.successfulResult(announcementApiData);
        } catch (Exception e) {
            log.error("AnnouncementAppService announcementList Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<FindAnnouncementVO> findAnnouncement(String accessToken, Long id) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("公告id为空");
            }

            Optional<Announcement> announcementOpt = announcementRepository.findById(id);
            if (!announcementOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("公告不存在");
            }
            Announcement announcement = announcementOpt.get();
            FindAnnouncementVO vo = new FindAnnouncementVO();
            vo.setId(announcement.getId());
            vo.setTitle(announcement.getTitle());
            vo.setContent(announcement.getContent());
            vo.setHomePic(announcement.getHomePic());
            vo.setReleaseTime(DateUtils.format(announcement.getReleaseTime(), DateUtils.FORMAT_DATETIME_14));
            //查询阅读量
            String view = redisTemplate.opsForValue().get("saas:announcement:view:" + id);
            if (StringUtils.isNotBlank(view)) {
                long viewCount = Long.parseLong(view);
                vo.setViewCount(viewCount);
            } else {
                vo.setViewCount(0L);
            }
            //查询点赞量
            String thumb = redisTemplate.opsForValue().get("saas:announcement:thumb:" + id);
            if (StringUtils.isNotBlank(thumb)) {
                long thumbCount = Long.parseLong(thumb);
                vo.setThumbCount(thumbCount);
            } else {
                vo.setThumbCount(0L);
            }
            //点赞状态
            AnnouncementUser au = announcementUserRepository.findByAnnouncementIdAndUserId(id, userId);
            if (au == null) {
                vo.setThumbStatus(0);
                //新增公告用户数据
                AnnouncementUser announcementUser = new AnnouncementUser();
                announcementUser.setAnnouncementId(id);
                announcementUser.setUserId(userId);
                announcementUser.setViewStatus(1);//已阅读
                announcementUser.setStatus(0);//未点赞
                announcementUser.setViewTime(new Date());
                announcementUserRepository.save(announcementUser);
            } else {
                vo.setThumbStatus(au.getStatus());
            }

            //redis缓存阅读量
            redisTemplate.opsForValue().increment("saas:announcement:view:" + id, 1);

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<HousePublicityData<HousePublicityVO>> findHousePublicity(String accessToken, Long id) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("公告id为空");
            }

            Optional<Announcement> announcementOpt = announcementRepository.findById(id);
            if (!announcementOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("公告不存在");
            }
            Announcement announcement = announcementOpt.get();
            //社区id
            Long areaId = announcement.getAreaId();

            HousePublicityData<HousePublicityVO> data = new HousePublicityData<>();
            data.setId(announcement.getId());
            data.setTitle(announcement.getTitle());
            data.setReleaseTime(DateUtils.format(announcement.getReleaseTime(), DateUtils.FORMAT_DATETIME_14));
            //查询阅读量
            String view = redisTemplate.opsForValue().get("saas:announcement:view:" + id);
            if (StringUtils.isNotBlank(view)) {
                long viewCount = Long.parseLong(view);
                data.setViewCount(viewCount);
            } else {
                data.setViewCount(0L);
            }
            //查询点赞量
            String thumb = redisTemplate.opsForValue().get("saas:announcement:thumb:" + id);
            if (StringUtils.isNotBlank(thumb)) {
                long thumbCount = Long.parseLong(thumb);
                data.setThumbCount(thumbCount);
            } else {
                data.setThumbCount(0L);
            }
            //点赞状态
            AnnouncementUser au = announcementUserRepository.findByAnnouncementIdAndUserId(id, userId);
            if (au == null) {
                data.setThumbStatus(0);
                //新增公告用户数据
                AnnouncementUser announcementUser = new AnnouncementUser();
                announcementUser.setAnnouncementId(id);
                announcementUser.setUserId(userId);
                announcementUser.setViewStatus(1);//已阅读
                announcementUser.setStatus(0);//未点赞
                announcementUser.setViewTime(new Date());
                announcementUserRepository.save(announcementUser);
            } else {
                data.setThumbStatus(au.getStatus());
            }
            //公示数据
            List<HousePublicityVO> list = jdbcTemplate.query("SELECT p.id,p.user_name AS userName,p.start_time AS startTime FROM saas_house_publicity p WHERE p.area_id = ? AND STR_TO_DATE(end_time,'%Y-%m-%d') > STR_TO_DATE(NOW(),'%Y-%m-%d') order by p.start_time desc",
                    new BeanPropertyRowMapper<>(HousePublicityVO.class), areaId);
            for (HousePublicityVO vo : list) {
                vo.setStartTime(DateUtils.format(vo.getStartTime(), DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
            }
            data.setData(list);

            //redis缓存阅读量
            redisTemplate.opsForValue().increment("saas:announcement:view:" + id, 1);

            return ResultBean.successfulResult(data);
        } catch (Exception e) {
            log.error("AnnouncementAppService findHousePublicity Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> thumb(String accessToken, Long id) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("公告id为空");
            }

            AnnouncementUser au = announcementUserRepository.findByAnnouncementIdAndUserId(id, userId);
            if (au == null) {
                return ResultBean.successfulResult(null);
            }
            if (au.getStatus() == 0) {//未点赞
                au.setStatus(1);
                au.setThumbTime(new Date());
                //增加点赞量
                redisTemplate.opsForValue().increment("saas:announcement:thumb:" + id, 1);
            } else if (au.getStatus() == 1) {//已点赞
                au.setStatus(0);
                au.setThumbTime(null);
                //redisson
                //RLock phoneLock = redisson.getLock("saas:announcement:thumb:" + id);
                //3秒后自动过期
                //phoneLock.lock(3, TimeUnit.SECONDS);
                //默认30秒, 如果10秒内未执行完，自动续期到30秒，释放锁时自动删除
                //phoneLock.lock();
                //减少点赞量
                String thumb = redisTemplate.opsForValue().get("saas:announcement:thumb:" + id);
                if (StringUtils.isNotBlank(thumb)) {
                    Long thumbCount = Long.valueOf(thumb);
                    if (thumbCount <= 0) {
                        redisTemplate.opsForValue().set("saas:announcement:thumb:" + id, "0");
                    } else {
                        thumbCount = thumbCount - 1;
                        redisTemplate.opsForValue().set("saas:announcement:thumb:" + id, thumbCount.toString());
                    }
                }
                // 释放锁
                //phoneLock.unlock();
            }
            announcementUserRepository.save(au);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    public ResultBean<Object> deleteAnnouncement(String accessToken, List<Long> idList) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();
            for (Long id : idList) {
                if (id == null) {
                    return ResultBean.failedResultOfParamWithMsg("公告id为空");
                }
                Optional<Announcement> announcementOpt = announcementRepository.findById(id);
                if (!announcementOpt.isPresent()) {
                    return ResultBean.failedResultWithMsg("公告不存在");
                }
                //新增删除状态
                AnnouncementUser au = announcementUserRepository.findByAnnouncementIdAndUserId(id, userId);
                if (au != null) {
                    au.setViewStatus(3);//已删除
                    announcementUserRepository.save(au);
                } else {
                    //新增公告用户数据
                    AnnouncementUser announcementUser = new AnnouncementUser();
                    announcementUser.setAnnouncementId(id);
                    announcementUser.setUserId(userId);
                    announcementUser.setViewStatus(3);//已删除
                    announcementUser.setStatus(0);//未点赞
                    announcementUser.setViewTime(new Date());
                    announcementUserRepository.save(announcementUser);
                }
            }
            return ResultBean.successfulResult("删除成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }

    }
    /**
     * 消息全部已读
     *
     * @param accessToken
     * @return
     */
    public ResultBean<Object> allRead(String accessToken,String communityId,Integer viewStatus) {
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        if (tokenRedisVo == null) {
            return ResultBean.failedResultOfToken();
        }
        String userId = tokenRedisVo.getId();

        String sql = " SELECT a.id FROM saas_announcement a WHERE a.status =1 AND a.id NOT IN (SELECT a.id FROM saas_announcement a LEFT JOIN saas_announcement_user u ON a.id = u.announcement_id WHERE u.user_id = ? )";
        //查询小区下公告消息 xiaolong 20230328
        List<Announcement> byCommunityId = jdbcTemplate.query( sql, new BeanPropertyRowMapper<>(Announcement.class), userId);
        //查询承租人房屋动态消息
        List<BacklogItem> byMatchUserId = backlogItemRepository.findByMatchUserId(userId);
        int num = 0;
        if (viewStatus == 0 ) {
            //计算承租人房屋动态消息未都数量
            if (byMatchUserId != null) {
                for (BacklogItem backlogItem : byMatchUserId) {
                    Integer handleStatus = backlogItem.getHandleStatus();
                    if (handleStatus == 0) {
                        num++;
                    }
                }
            }
            //计算小区下公告消息未都数量
            for (Announcement announcement : byCommunityId) {
                //获取公告id
                Long id = announcement.getId();
                //查询公告与用户表
                AnnouncementUser announcementUser = announcementUserRepository.findByAnnouncementIdAndUserId(id, userId);

                if (announcementUser == null ) {
                    num++;
                }
                if (announcementUser != null ) {
                    Integer status = announcementUser.getStatus();
                    if (status == 3 || status == 1) {
                        num--;
                    }
                }
            }
            return ResultBean.successfulResult(num);

        } else {
            //更改房屋消息状态
            if (byMatchUserId != null) {
                for (BacklogItem backlogItem : byMatchUserId) {
                    Integer handleStatus = backlogItem.getHandleStatus();
                    if (handleStatus == 0) {
                        backlogItem.setHandleStatus(1);
                        backlogItemRepository.save(backlogItem);
                    }

                }
            }
            //更改公告消息状态
            for (Announcement announcement : byCommunityId) {
                //获取公告id
                Long id = announcement.getId();
                //查询公告与用户表
                AnnouncementUser announcementUser = announcementUserRepository.findByAnnouncementIdAndUserId(id, userId);
                if (announcementUser == null) {
                    announcementUser = new AnnouncementUser();
                    announcementUser.setAnnouncementId(id);
                    announcementUser.setUserId(userId);
                    announcementUser.setViewStatus(1);//已阅读
                    announcementUser.setStatus(0);//未点赞
                    announcementUser.setViewTime(new Date());
                    announcementUserRepository.save(announcementUser);
                }
            }
            return ResultBean.successfulResult("全部已读！");
        }

    }
}
